package app

import (
	"encoding/json"
	"os/exec"
	"path/filepath"
	"strconv"

	"gitee.com/extrame/fb-runner/util"
	"github.com/sirupsen/logrus"
)

func Commit(base string, codes *Chaincode, force bool) error {
	var codeMap = make(map[string]*Chaincode)
	if codes == nil {
		codeMap = GetInstalledChaincodes()
	} else {
		codeMap[codes.PackageId] = codes
	}
	orderer := util.Config.GetOrdererOrganization()
	ordererPeer, _ := orderer.GetLocalPeer(true)
	for _, c := range codeMap {
		if (c.Commited || c.Historic) && !force {
			logrus.WithField("commited", c.Commited).WithField("Historic", c.Historic).WithField("force", force).Infoln("跳过")
			continue
		}
		var args = []string{
			"lifecycle", "chaincode", "commit", "-o",
			ordererPeer.GetUrl(), "--ordererTLSHostnameOverride", ordererPeer.GetHost(),
			"--channelID", c.Channel, "--name", c.Name, "--version", c.VersionLabel, "--init-required",
			"--sequence", strconv.FormatUint(c.Version, 10), "--tls", "true",
			"--cafile", filepath.Join(base, "organizations", orderer.GetParentDir(), orderer.GetHost()+"/tlsca/tlsca."+orderer.GetHost()+"-cert.pem"),
		}
		cmd := exec.Command("peer", args...)
		var has = false
		for _, org := range util.Config.GetPeerOrganizations() {
			if !has {
				util.UseOrg(cmd, base, org, true)
			}
			p, _ := org.GetLocalPeer(true)
			cmd.Args = append(cmd.Args, "--peerAddresses", p.GetUrl(), "--tlsRootCertFiles", p.GetTlsCaPath(base))
		}
		logrus.Infoln("执行命令:" + cmd.String())
		_, _, err := util.Run(cmd)
		if err != nil {
			return err
		}

		logrus.Info("完成提交：", c)
		c.Commited = true
		UpdateChaincode(c)
	}
	return nil
}

func CheckCommit(base string) error {
	//peer lifecycle chaincode install ~/anhui1.tar.gz
	for _, org := range util.Config.GetPeerOrganizations() {
		cmd := exec.Command("peer", "lifecycle", "chaincode", "queryapproved", "--output", "json", "-C")
		util.UseOrg(cmd, base, org, true)
		stdout, _, err := util.Run(cmd)
		if err != nil {
			return err
		}
		var out OutputJson
		json.Unmarshal([]byte(stdout), &out)
		newCode := CheckNewInstall(out.InstalledChaincodes)
		logrus.Info("完成安装确认：", newCode)
		AddChaincode(newCode...)
	}
	return nil
}
